package icu.zhhll.datasource.dynamic;

import icu.zhhll.datasource.common.DataSourceHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @author zh
 * @date 2023/10/7 16:48
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);

    private String defaultDs;

    public String getDefaultDs() {
        return defaultDs;
    }

    void setDefaultDs(String defaultDs) {
        this.defaultDs = defaultDs;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String key = DataSourceHolder.getCurDataSource();
        LOGGER.debug("{}线程 获取到的数据源key--->{}", Thread.currentThread().getName(), key);

        if (StringUtils.isBlank(key)) {
            key = defaultDs;
        }
        LOGGER.debug("{}线程 数据源选择--->{}", Thread.currentThread().getName(), key);
        return key;
    }
}
